package com.kay.client;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.mail.*;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;


@Component
@Slf4j
@RefreshScope
public class SendMailClient {

    @Value("${email.smtp.host}")
    private String host;

    @Value("${email.smtp.port}")
    private String port;

    @Value("${email.user}")
    private String user;

    @Value("${email.password}")
    private String password;

    //配置发送邮件的环境属性
    final Properties props = new Properties();

    private Authenticator authenticator;

    // 关键3
    @PostConstruct
    public void init() {
        // 构建授权信息，用于进行SMTP进行身份验证
        authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password);
            }
        };
        // 表示SMTP发送邮件，需要进行身份验证
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", host);
        //SSLSocketFactory类的端口
        props.put("mail.smtp.socketFactory.port", port);
        //SSLSocketFactory类
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        //网易提供的ssl加密端口,QQ邮箱也是该端口
        props.put("mail.smtp.port", port);
        //smtp登陆的账号、密码 ；需开启smtp登陆
        props.put("mail.user", user);
        // 访问SMTP服务时需要提供的密码,不是邮箱登陆密码，一般都有独立smtp的登陆密码
        props.put("mail.password", password);
    }

    /*
     * mailAdr 收件人地址
     * subject 邮件标题
     * content 邮件文本内容
     */
    @Async
    public void sendMail(String mailAdr,String subject,String content) throws MessagingException {
        // 使用环境属性和授权信息，创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession);
        try{
            message.setFrom(new InternetAddress(user));
            // 设置收件人
            message.setRecipient(RecipientType.TO, new InternetAddress(mailAdr));
            // 设置抄送  避免出现 554 错误（垃圾邮件）
            message.setRecipient(RecipientType.CC, new InternetAddress(user));

            // 设置密送，其他的收件人不能看到密送的邮件地址
            //message.setRecipient(RecipientType.CC, new InternetAddress("aaaaa@163.com"));
            // 设置邮件标题
            message.setSubject(subject);
            // 设置邮件的内容体
            message.setContent(content, "text/html;charset=UTF-8");
            // 发送邮件
            Transport.send(message);
        }catch(MessagingException e){
            e.printStackTrace();
            log.error("邮箱,{}，发送失败，主题,{}，内容, {}", mailAdr, subject, content);
            throw  e;
        }
    }
}
